#include "Scores.h"

namespace qtangram {
    Scores::Scores(QWidget* parent) : QDialog(parent), magicNr(0x12321) {
	setupUi(this);
	connect(closeButton, SIGNAL(clicked()), this, SLOT(hide()));
	connect(clearButton, SIGNAL(clicked()), this, SLOT(onClearClicked()));

	itemList.clear();
	QFile file("hs.dat");
	file.open(QIODevice::ReadOnly);
	QDataStream in(&file);
	quint32 check;
	quint16 quantity;
	in >> check >> quantity;
	if(check != magicNr) std::cerr << "Wrong hs.dat file format\n";
	else {
	    quint16 secs;
	    QString time, name;
	    for(int i = 0; i < quantity; ++i) {
		in >> secs >> time >> name;
		itemList.insert(ScoresItem(secs,time,name));
	    }
	}
    }

    Scores::~Scores() {
	int quantity;
	itemList.size() >= 10 ? quantity = 10 : quantity = itemList.size();
	QFile file("hs.dat");
	file.open(QIODevice::WriteOnly);
	QDataStream out(&file);
	out << magicNr << static_cast<quint16>(quantity);
	auto it = itemList.begin();
	for(int i = 0; i < quantity; ++it, ++i) {
	    out << static_cast<quint16>(std::get<0>(*it));
	    out << std::get<1>(*it);
	    out << std::get<2>(*it);
	}
    }

    void Scores::onClearClicked() {
	itemList.clear();
	display();
    }

    void Scores::add(ScoresItem item) {
	itemList.insert(item);
    }

    void Scores::display() {
	table->clearContents();
	auto it = itemList.begin();
	int i;
	for(i = 0; it != itemList.end() && i < 10; ++it, ++i) {
	    table->setItem(i,0,new QTableWidgetItem(std::get<1>(*it)));
	    table->setItem(i,1,new QTableWidgetItem(std::get<2>(*it)));
	}
	show();
    }
}
